#include "POLYGON.H"

boolean loadPolygon(const char* fileName, Polygon* drawing){
	int x = 0, y = 0, z = 0;
	boolean retVal = FALSE;
	int j =0;
	int width = 0, height =0, vertexCount = 0;
	FILE* fp = fopen(fileName, "r");
	if(fp != NULL){
		fscanf(fp, "%d", &vertexCount);
		drawing->vertexCount  = vertexCount;
		drawing->vertices = (Point*)(malloc(sizeof(Point)*vertexCount));
		if(drawing->vertices != NULL){
			width = 0;
			height = 0;
			for(j=0;j<vertexCount;j++){
				fscanf(fp, "%d %d %d", &x, &y, &z);
				if(width < x){
					width = x;
				}
				if(height < y){
					height = y;
				}
				drawing->vertices[j].x = x;
				drawing->vertices[j].y = y;
				drawing->vertices[j].pen = z;
			}
			drawing->height = height;
			drawing->width = width;
			retVal = TRUE;
		}
		else{
			printf("Error allocating memory\n");
		}
		fclose(fp);
	}	
	else{
		printf("Error opening file\n");
	}	
	return retVal;
}
void freePolygon(Polygon* polygon){
	free(polygon->vertices);
}
void drawPolygon(Polygon polygon, int posX, int posY, byte color){
	int i;
	for (i=0; i<(polygon.vertexCount)-1; i++){
		if(polygon.vertices[i+1].pen == 1){
			drawLine(posX+polygon.vertices[i].x, posY+polygon.vertices[i].y, posX+polygon.vertices[i+1].x, posY+polygon.vertices[i+1].y, color);
		}
	}
}
void drawClippedScreenPolygon(Polygon polygon, int posX, int posY, byte color, Region clipPlane){
	boolean visible;
	Line old, clipped;
	int i;
	for (i=0; i<(polygon.vertexCount)-1; i++){
		if(polygon.vertices[i+1].pen == 1){			
			old.x0 = posX+polygon.vertices[i].x;
			old.y0 = posY+polygon.vertices[i].y;
			old.x1 = posX+polygon.vertices[i+1].x;
			old.y1 = posY+polygon.vertices[i+1].y;
			visible = clipLineToScreen(old, &clipped, clipPlane);
			if (visible) drawLine(clipped.x0, clipped.y0, clipped.x1, clipped.y1, color);
		}
	}
}
void drawClippedPolygon(Polygon polygon, int posX, int posY, byte color, Region clipPlane, Region viewPort){
	boolean visible;
	Line old, clipped;
	int i;
	for (i=0; i<(polygon.vertexCount)-1; i++){
		if(polygon.vertices[i+1].pen == 1){
			old.x0 = posX+polygon.vertices[i].x;
			old.y0 = posY+polygon.vertices[i].y;
			old.x1 = posX+polygon.vertices[i+1].x;
			old.y1 = posY+polygon.vertices[i+1].y;
			visible = clipLine(old, &clipped, clipPlane, viewPort);
			if (visible) drawLine(clipped.x0, clipped.y0, clipped.x1, clipped.y1, color);
		}
	}
}
